package com.lh.job.task;

import com.lh.common.entity.admin.Order;
import com.lh.common.entity.admin.OrderStatusLog;
import com.lh.common.entity.state.RemarkEnum;
import com.lh.common.enums.IF;
import com.lh.common.enums.OrderStatusEnum;
import com.lh.common.utils.MathUtil;
import com.lh.job.dao.OrderMapper;
import com.lh.job.dao.OrderStatusLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author gze
 * @ClassName: OrderShipedTask
 * @Description: (订单自动收货定时任务)
 * @date: 2020-05-29 16:01
 */
@Component("orderShipedTask")
@Slf4j
public class OrderShipedTask implements ITask{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderStatusLogMapper orderStatusLogMapper;

    /*
     * 已发货后15天自动转成已完成，插入订单记录表 每小时检查一次
     * */
    @Transactional
    @Override
        // 0 0 */1 * * ?
    public void run(String day) {
        log.info("自动收货任务开始！！！");
        boolean bool = MathUtil.isNumber(day);
        if (!bool || day == null) {
            day = "15";
        }

        //查询出所有已发货状态的订单
        List<Order> orderList = orderMapper.overtimeOrder(OrderStatusEnum.SHIPED, day);
        List<Order> orderUpList = new ArrayList<>();
        List<OrderStatusLog> logList = new ArrayList<>();
        if(orderList != null && !orderList.isEmpty()){
            for (Order order : orderList) {
                OrderStatusLog orderStatusLog = new OrderStatusLog();
                orderStatusLog.setUserId(order.getUserId());
                orderStatusLog.setOrderId(order.getOid());
                orderStatusLog.setOldStatus(OrderStatusEnum.SHIPED);
                orderStatusLog.setNewStatus(OrderStatusEnum.COMPLETED);
                orderStatusLog.setCreateTime(new Date());
                orderStatusLog.setUpdateTime(new Date());
                orderStatusLog.setIsSys(IF.NO);
                orderStatusLog.setRemark(RemarkEnum.SHZT07);
                logList.add(orderStatusLog);

                Order orderUp = new Order();
                orderUp.setOid(order.getOid());
                orderUp.setUpdateTime(new Date());
                orderUp.setOrderStatus(OrderStatusEnum.COMPLETED);
                orderUp.setSignTime(new Date());
                orderUpList.add(orderUp);
            }
            //批量更新订单表
            orderUpList.stream().forEach(orderMapper::updateByKey);

            //批量插入记录表
            orderStatusLogMapper.insertBatchLog(logList);
        }
        log.info("自动收货任务结束！！！");
    }

}
